package myLearnjdk.jdk.net.ssl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.SocketFactory;
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

/**
 * 客户端Socket加密练习
 * @author yangcheng  
 * @date 2020年8月12日  
 * @version V1.0
 */
public class SSLtest {

	public static void main(String[] args) throws UnknownHostException, IOException {
		startClient();
	}
	
	public static void startClient() throws UnknownHostException, IOException{
		SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
		SSLSocket socket = (SSLSocket) factory.createSocket("www.baidu.com", 443);
		/**
		 * 通过监听器的方式  异步的处理安全连接的握手事件
		 */
		socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
			
			@Override
			public void handshakeCompleted(HandshakeCompletedEvent event) {
				System.out.println("握手完成，当前Socket使用的加密算法是=="+event.getCipherSuite());
				
			}
		});
		/**
		 * 从服务端获取ssl证书的所有可用的算法组合
		 */
		String[] ciphers = socket.getSupportedCipherSuites();
		
		socket.setEnabledCipherSuites(ciphers);//将服务端证书选项设置到客户端中
		for (String string : ciphers) {
			System.out.println(string);
		}
		
		/**
		 * 获取当前socket允许可以使用的安全算法
		 */
		String[] enableCiphers = socket.getEnabledCipherSuites();
		for (String string : enableCiphers) {
			System.out.println(string);
		}
		
		/**
		 * 设置socket只使用某个加密算法
		 * 
		 * handshake_failure标识tls握手失败
		 */
//		String[] array = {"TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"};
//		socket.setEnabledCipherSuites(array);
		
		/**
		 * 向服务器发起请求，以便接收到http响应
		 */
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
		writer.write("GET http://www.baidu.com HTTP/1.1\r\n");
		writer.write("HOST: www.baidu.com\r\n");
		writer.write("\r\n");
		writer.flush();
		
		
		BufferedReader breader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		String str = null;
		while(!(str = breader.readLine()).equals("")){
			
			System.out.println(str);
		}
		
	}
}
